import React, { useEffect, useState } from 'react'
import {
  Card,
  Button,
  Table,
  Image,
  Modal,
  Form,
  Input,
  Upload,
  message
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table/interface';
import { reqAddTrademark, reqDeleteTrademark, reqTrademarkList, reqTrademarkReturnItemType, reqTrademarkReturnRecordsType, reqUpdateTrademark } from '@/api/trademark';
import { RcFile, UploadProps } from 'antd/lib/upload';



function index() {

  // 状态1 品牌信息
  const [tabelData, setTabelData] = useState<reqTrademarkReturnRecordsType>([])
  // 页码数据
  const [pageInfo, setPageInfo] = useState({
    current: 1, // 当前页
    pageSize: 5, // 每页几个数据
    total: 10  // 数据总数量
  })


  // 表单列数据
  const columns: ColumnsType<reqTrademarkReturnItemType> = [
    {
      title: '序号',
      align: "center",
      key: 'index',
      render(values, rows, index) {
        return (pageInfo.current - 1) * pageInfo.pageSize + index + 1
      }
    },
    {
      title: '品牌名称',
      dataIndex: 'tmName',
      align: "center",
      key: 'tmName'
    },
    {
      align: "center",
      title: '品牌Logo',
      dataIndex: 'logoUrl',
      key: 'logoUrl',
      render(values) {
        return <Image height={50} src={values} />
      }
    },
    {
      align: "center",
      title: '操作',
      render: (row) => (
        <>
          {/* 模板中书写方法 onClick={() => updateTra(row)} 用箭头函数  */}
          <Button type="primary" icon={<EditOutlined />} style={{ marginRight: '3px' }} onClick={() => updateTra(row)}>
            修改
          </Button>
          <Button danger icon={<DeleteOutlined />} onClick={() => deleteTra(row.id)}>
            删除
          </Button>
        </>
      )
    }
  ]


  // 封装请求品牌列表方法
  const getTrademarkList = async (current: number, pageSize: number) => {
    setLoading(true)
    try {
      const res = await reqTrademarkList(current, pageSize)
      // 获取品牌列表
      setTabelData(res.records)
      // 获取页码
      setPageInfo({
        current: res.current,
        pageSize: 5,
        total: res.total
      })
    } catch (e) {
      return Promise.reject(e)
    }
    setLoading(false)
  }

  // 页面是否在加载中
  const [loading, setLoading] = useState<boolean>(false);

  // 新增或修改 图片
  const [logoUrl, setLogoUrl] = useState<string>('')
  // 新增或修改的数据
  const [tardeForm, settradeForm] = useState<any>({})

  // 状态2 对话框是否显示
  const [isModal, setIsModal] = useState(false)

  // 添加品牌事件
  const addTrade = () => {
    setIsModal(true)
  }

  // 修改品牌事件
  const updateTra = (row: reqTrademarkReturnItemType) => {
    setLogoUrl(row.logoUrl)
    form.setFieldsValue(row) // 回填数据
    setIsModal(true)
  }

  // 删除事件
  const deleteTra = async (id: number) => {
    await reqDeleteTrademark(id)
    getTrademarkList(1, 5)
  }


  // 对话框点击取消事件
  const modalCancel = () => {
    setIsModal(false)
    settradeForm({
      tmName: '',
      logoUrl: ''
    })
    setLogoUrl('')
  }


  //  表单提交事件
  const onFinsh = async (values: any) => {
    try {
      if (tardeForm.id) {
        // 修改
        await reqUpdateTrademark({ ...tardeForm, ...values, logoUrl })
        message.success('修改成功')
      } else {
        // 新增
        await reqAddTrademark({ ...tardeForm, ...values, logoUrl })
        message.success('添加成功')
      }
      // 清空表单
      settradeForm({
        tmName: '',
        logoUrl: ''
      })
      setLogoUrl('')

      // 关闭对话框
      setIsModal(false)
      // 重新请求数据
      getTrademarkList(1, 5)
    } catch (e) {
      message.error('新增或修改失败')
    }

  }

  // 限制用户上传图片事件
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  // 拿到上传图片的地址
  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'done') {
      setLogoUrl(info.file.response.data)
    }
  }

  useEffect(() => {
    getTrademarkList(pageInfo.current, pageInfo.pageSize)
  }, [])

  const [form] = Form.useForm() // 实例化form

  return (
    <div>
      <Card title="品牌列表" extra={<Button type="primary" onClick={addTrade} >添加</Button>}>
        <Table
          rowKey={"id"}
          loading={loading}
          columns={columns}
          dataSource={tabelData}
          pagination={{
            ...pageInfo,
            onChange: getTrademarkList
          }}
        />

        <Modal
          title="添加品牌"
          width={'980px'}
          maskClosable={true}
          visible={isModal}
          footer={null}
        >
          <Form
            name="basic"
            form={form}
            onFinish={onFinsh}
          >
            <Form.Item
              label="品牌名称"
              name="tmName"
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="品牌logo"
            >
              <Upload
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                {logoUrl ?
                  <img src={logoUrl} width={80} />
                  :
                  <div>
                    <PlusOutlined />
                    <div style={{ marginTop: 8 }}>Upload</div>
                  </div>
                }
              </Upload>
            </Form.Item>

            <Form.Item >
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button htmlType="button" onClick={modalCancel}>
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  )
}

export default index